package com.lwx.geoip;

import java.io.IOException;
import java.net.InetAddress;

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.model.CountryResponse;

public class GeoipMain {
    private static DatabaseReader reader;
    static{
        try {
            reader = new DatabaseReader.Builder(GeoipMain.class.getClassLoader().getResourceAsStream("GeoLite2-Country.mmdb")).build();
        } catch (Exception e) {
            throw new RuntimeException("GeoLite2 database initialization", e);
        }
    }

    public static String getCountryCodeByIP(String ipAddr) throws IOException, GeoIp2Exception {
        InetAddress ipAddress = InetAddress.getByName(ipAddr);
        CountryResponse response = reader.country(ipAddress);
        return response.getCountry().getIsoCode();
    }
    
    public static void main(String[] args) throws IOException, GeoIp2Exception {
        System.err.println(getCountryCodeByIP("202.104.148.18"));
    }
}
